package com.kfm.jdbc.day01;

import java.sql.*;

public class Transfer02 {

    public static void main(String[] args) {
        transfer("老兵", "新兵", 10);
    }



    public static void transfer(String from, String to, double money) {
        // 简化操作 直接做转账操作
        String url = "jdbc:mysql://localhost:3306/company_info";
        String user = "root";
        String pass = "root";

        // 根据姓名修改 余额
        String sql = "update customer set balance = balance - ? where customerName = ?";
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, user, pass);
            // 开启事务
            connection.setAutoCommit(false);

            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            // 设置值
            preparedStatement.setObject(1, money);
            preparedStatement.setObject(2, from);
            // 扣钱
            preparedStatement.executeUpdate();


//            int a = 1 / 0;

            // 设置值
            preparedStatement.setObject(1, -money);
            preparedStatement.setObject(2, to);

            // 加钱
            preparedStatement.executeUpdate();

            // 提交事务
            connection.commit();
        } catch (SQLException e) {
            try {
                // 回滚事务
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        } finally {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }


    }
}
